package com.mianyang.zhangsan.model.dto;

import com.alibaba.fastjson.JSONArray;
import com.mianyang.zhangsan.model.entity.SecAnswer;
import com.mianyang.zhangsan.model.entity.SecProblemInst;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author jiangjr
 * @date 2022-11-30
 */
@Data
@Builder
public class SecProblemDto {
    @ApiModelProperty(value = "问题")
    private SecProblemInst problem;

    @ApiModelProperty(value = "答案")
    private List<SecAnswer> answers;

    public int computeUserAnswer(JSONArray userAnswer) {
        int score = 0;
        boolean isCorrect = true;
        if (userAnswer != null) {
            for (Object answer : userAnswer) {
                if (answer != null) {
                    long answerId = Long.parseLong(answer.toString());
                    if (answers != null) {
                        Optional<SecAnswer> selectedAnswer = answers.stream()
                                .filter(item -> item.getAnswerId().equals(answerId)).findFirst();
                        if (selectedAnswer.isPresent()) {
                            SecAnswer secAnswer = selectedAnswer.get();
                            if (secAnswer.getIsRight() == 1) {
                               if (isCorrect) {
                                   score += secAnswer.getScore();
                               }
                            } else {
                                score = 0;
                                isCorrect = false;
                            }
                        }
                    }
                    // todo 多选情况
                    // update user answer
                    problem.setUserAnswer(answerId);
                    if (isSelectedOnce()) {
                        break;
                    }
                }
            }
        }
        return score;
    }

    public boolean isSelectedOnce() {
        return problem.getProblemType() == 1;
    }
}
